package com.vidmt.api.modules.sys.providers.impl;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.google.common.collect.Lists;
import com.vidmt.api.common.utils.CommUtil;
import com.vidmt.api.modules.sys.providers.ResProvider;

public class OssResProvider implements ResProvider {
	private static final Logger log = LoggerFactory.getLogger(OssResProvider.class);
	// endpoint以杭州为例，其它region请按实际情况填写
	String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
	// accessKey请登录https://ak-console.aliyun.com/#/查看
	String accessKeyId = "<yourAccessKeyId>";
	String accessKeySecret = "<yourAccessKeySecret>";
	String bucketName = "<yourBucketName>";

	private OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

	@Override
	public void uploadFile(String relpath, InputStream file) throws IOException {
		client.putObject(bucketName, relpath, file);
	}

	@Override
	public byte[] downloadFile(String relpath) throws IOException {
		// 下载object到文件
		ByteArrayOutputStream bao = null;
		BufferedInputStream bis = null;
		try {
			OSSObject ossObject = client.getObject(bucketName, relpath);
			bao = new ByteArrayOutputStream();

			byte[] buff = new byte[4 * 1024];
			int len = -1;
			InputStream is = ossObject.getObjectContent();
			bis = new BufferedInputStream(is);
			while (((len = bis.read(buff)) > 0)) {
				bao.write(buff, 0, len);
			}
			return bao.toByteArray();
		} finally {
			CommUtil.close(bao, bis);
		}
	}

	@Override
	public void deleteFile(String relpath) throws IOException {
		ListObjectsRequest findReq = new ListObjectsRequest(bucketName);
		findReq.setPrefix(relpath);
		// 递归列出fun目录下的所有文件
		ObjectListing listing = client.listObjects(findReq);
		System.out.println("Objects:");
		List<String> keys = Lists.newArrayList();
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			keys.add(objectSummary.getKey());
		}

		DeleteObjectsRequest deleteReq = new DeleteObjectsRequest(bucketName).withKeys(keys);
		deleteReq.setQuiet(true);
		DeleteObjectsResult deleteObjectsResult = client.deleteObjects(deleteReq);
		List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
		for (String object : deletedObjects) {
			log.info("删除文件" + object);
		}
	}

}
